<template>
	<div class="searchContainer">
		<form class="search-form" action="/">
		  <van-search
		    v-model="searchText"
		    show-action
			background="#3296fa"
		    placeholder="请输入搜索关键词"
		    @cancel="$router.back()"
			@search="onSearch"
			@focus="isShowResult=false"
		  />
		</form>
		<!-- 搜索结果 -->
		<search-result v-if="isShowResult" :q="searchText"></search-result>
		<!-- 联想建议 -->
		<search-suggesstion v-else-if='searchText' :q="searchText" @search="onSearch"></search-suggesstion>		
		<!-- 历史记录 -->
		<search-history v-else v-model="historySearch" @search="onSearch"></search-history>
	</div>
</template>

<script>
	import searchHistory from './searchCmp/search-history.vue'
	import searchSuggesstion from './searchCmp/search-suggesstion.vue'
	import searchResult from './searchCmp/search-result.vue'
	import {getItem,setItem} from '@/utils/storage.js'
	export default {
		name:'search',
		data(){
			return {
				searchText:'',
				isShowResult:false,
				historySearch:getItem('historyList')||[]
			}
		},
		components:{
			searchHistory,
			searchSuggesstion,
			searchResult
		},
		methods:{
			onSearch(q){
				
				this.searchText = q
				// 检测是否有重复的搜索记录
				const index = this.historySearch.indexOf(q)
				if(index != -1){
					this.historySearch.splice(index,1)
				}
				this.historySearch.unshift(q)
				this.isShowResult=true
			}
		},
		watch:{
			historySearch(newVal){
				setItem('historyList',newVal)
			}
		}
	}
</script>

<style scoped lang="less">
	.searchContainer{
		padding-top:54px;
		.search-form{
			position:fixed;
			top:0;
			left:0;
			right:0;
			z-index: 1;
		}
	}
</style>
